package com.ifonly.common.typeconverter.impl;

import com.ifonly.common.typeconverter.Converter;
import com.ifonly.common.typeconverter.TypeConversionException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 21:46
 * @since JDK 1.6
 */
public class ClassConverter implements Converter<Class> {
    @Override
    public Class convert(Object value) {
        if (value == null) {
            return null;
        }

        if (value.getClass() == Class.class) {
            return (Class) value;
        }
        try {
            String className = value.toString().trim();

            if (className.endsWith(".class")) {
                className = className.substring(0, -6);
            }

            return Class.forName(className);
        } catch (ClassNotFoundException cnfex) {
            throw new TypeConversionException(value, cnfex);
        }
    }
}
